var area = require('../../utils/area.js')
var areaInfo = []; //所有省市区县数据
var provinces = [];
var citys = [];
var countys = [];
var index = [0, 0, 0];
var t = 0;
var show = true;
var moveY = 200;
Page({
  data: {
    couponid:0,
    contents: '',
    name: '',
    phone: '',
    address: '',
    province: '',
    city: '',
    region: '',
    num: 1, //数量
    price: '',
    nowprice: 0, //现价
    total_price: 0, //总价
    del_price: 0, //抵现
    goodid: '',
    list1: [],
    userId: '',
    show: show,
    provinces: '',
    citys: '',
    countys: '',
    value: [0, 0, 0]
  },
  //获取默认地址
  myaddress: function() {
    var that = this;
    var req = {
      token: that.data.token,
      userid: that.data.userId
    }
    my.request({ // 调用自己的服务端接口，让服务端进行后端的授权认证，并且种session，需要解决跨域问题
      url: 'https://www.tiantong369.com/crm/usershopaddresslist', // 该url是自己的服务地址
      method: 'POST',
      headers: {
        // 'x-access-token': that.data.token
      },
      data: req,
      dataType: 'json',
      success: (res) => {// 成功获取订单号
        for (var i = 0; i < res.data.data.msg.length; i++) {
          if (res.data.data.msg[i].isdefault == '是') {
            var req = {
              id: res.data.data.msg[i].id
            }
            my.request({ // 调用自己的服务端接口，让服务端进行后端的授权认证，并且种session，需要解决跨域问题
              url: 'https://www.tiantong369.com/crm/usershopaddressinfo', // 该url是自己的服务地址
              method: 'POST',
              headers: {
                // 'x-access-token': that.data.token
              },
              data: req,
              dataType: 'json',
              success: (res) => {// 成功获取订单号
                if (res.data.status == 200) {
                  that.setData({
                    name: res.data.data.truename,
                    phone: res.data.data.phone,
                    address: res.data.data.address,
                    province: res.data.data.province,
                    city: res.data.data.city,
                    region: res.data.data.region,
                    isdefault: res.data.data.isdefault,
                  })
                } else {
                  my.showToast({
                    success: (res) => {
                      content: res.data.message
                    }
                  });
                }


              },
              fail: (res) => {
                console.log('GetEmpPrice:', res)
              },
            });
          }
        }
      },
      fail: (res) => {
        console.log('GetEmpPrice:', res)
      },
    });
  },
  // 获取我的优惠券
  mycoupon: function() {
    var pages = getCurrentPages()
    var page = pages[pages.length - 2]
    var that = this;
    that.setData({
      num: page.data.num,
      nowprice: page.data.nowprice,
      goodid: page.data.goodid,
      total_price: (page.data.nowprice * page.data.num)
    });
    var req = {
      money: that.data.total_price,
      userid: that.data.userId
    }
    my.request({ // 调用自己的服务端接口，让服务端进行后端的授权认证，并且种session，需要解决跨域问题
      url: 'https://www.tiantong369.com/crm/usercoupon', // 该url是自己的服务地址
      method: 'POST',
      headers: {
        // 'x-access-token': that.data.token
      },
      data: req,
      dataType: 'json',
      success: (res) => {// 成功获取订单号
        if (res.data.status == 200) {
          var arr = [];
          for (var i = 0; i < res.data.data.length; i++) {
            arr.push(res.data.data[i])
            if (res.data.data[i].choose == true) {
              that.setData({
                couponid: res.data.data[i].couponid,
                del_price: res.data.data[i].jian,
                total_price: that.data.total_price - res.data.data[i].jian,
              })

            }
          }

          that.setData({
            list1: arr,
          })

        } else {
          my.showToast({
            success: (res) => {
              content: res.data.message
            }
          });
        }


      },
      fail: (res) => {
        console.log('GetEmpPrice:', res)
      },
    });
  },
  // ------------------- 分割线 --------------------
  onReady: function() {
    this.animation = my.createAnimation({
      transformOrigin: "50% 50%",
      duration: 0,
      timingFunction: "ease",
      delay: 0
    })
    this.animation.translateY(200 + 'vh').step();
    this.setData({
      animation: this.animation.export(),
      show: show
    })
  },
  //滑动事件
  bindChange: function(e) {
    var val = e.detail.value
    //判断滑动的是第几个column
    //若省份column做了滑动则定位到地级市和区县第一位
    if (index[0] != val[0]) {
      val[1] = 0;
      val[2] = 0;
      getCityArr(val[0], this); //获取地级市数据
      getCountyInfo(val[0], val[1], this); //获取区县数据
    } else { //若省份column未做滑动，地级市做了滑动则定位区县第一位
      if (index[1] != val[1]) {
        val[2] = 0;
        getCountyInfo(val[0], val[1], this); //获取区县数据
      }
    }
    index = val;
    //更新数据
    this.setData({
      value: [val[0], val[1], val[2]],
      province: provinces[val[0]].text,
      city: citys[val[1]].text,
      region: countys[val[2]].text
    })

  },
  //移动按钮点击事件
  translate: function(e) {
    if (t == 0) {
      moveY = 0;
      show = false;
      t = 1;
    } else {
      moveY = 200;
      show = true;
      t = 0;
    }
    animationEvents(this, moveY, show);

  },
  //隐藏弹窗浮层
  hiddenFloatView(e) {
    moveY = 200;
    show = true;
    t = 0;
    animationEvents(this, moveY, show);

  },
  formName: function(e) {
    this.setData({
      name: e.detail.value
    })
  },
  formphone: function(e) {
    this.setData({
      phone: e.detail.value
    })
  },
  formaddress: function(e) {
    this.setData({
      address: e.detail.value
    })
  },
  formcontents: function(e) {
    this.setData({
      contents: e.detail.value
    })
  },

  //支付
  buy() {
    var that = this;
    that.setData({
      hidden:true
    })
    //正则匹配
    var mobile = /^[1][3,4,5,6,7,8,9][0-9]{9}$/;
    // var myreg = /^(([0\+]\d{2,3}-)?(0\d{2,3})-)(\d{7,8})(-(\d{3,}))?$/;  //判断是否是座机电话
    var isMobile = mobile.exec(that.data.phone)
    if (that.data.name == '' || that.data.phone == '' || that.data.address == '') {
      my.showToast({
        content: '请完整填写信息',
      });
    } else if (!isMobile) {
      my.showToast({
        content: '你输入的电话不符，请重新检查填写',
      });
    } else {
      my.getAuthCode({ // 获取用户code
        scopes: 'auth_user', // 主动授权（弹框）：auth_user，静默授权（不弹框）：auth_base
        success: (res) => {
          if (res.authCode) { // 认证成功
            var req = {
              ucode: res.authCode,
              token: that.data.token,
              num: that.data.num,
              userid: that.data.userId,
              DevID: that.data.deviceid,
              openid: that.data.openId,
              goodid: that.data.goodid,
              truename: that.data.name,
              phone: that.data.phone,
              province: that.data.province,
              city: that.data.city,
              region: that.data.region,
              address: that.data.address,
              contents: that.data.contents,
              couponid: that.data.couponid,
            }



            my.request({ // 调用自己的服务端接口，让服务端进行后端的授权认证，并且种session，需要解决跨域问题
              url: 'https://www.tiantong369.com/crm/goodalipay', // 该url是自己的服务地址
              method: 'POST',
              data: req,
              headers: {
                // 'x-access-token': this.data.token
              },
              success: (res) => {//
                console.log('7774', res)
                this.setData({ hidden: false })
                if (res.status == 200) {
                  var that = this;
                 my.tradePay({// 调用此方法唤起支付宝收银台item
                  tradeNO: res.data.tradeNo,
                  success: function(res) {
                    if (res.resultCode != '6001') { // 付款成功
                      my.alert({ content: '购买成功,等待卖家发货。。。' });
                    } else { // 用户点了×，并未付款
                      my.alert({ content: '付款失败' });
                    }
                  },
                  fail: function(res) {
                    // console.log('fail', res)
                  },
                });
                }


              },
              fail: (res) => {
                console.log('fail:', res)
              },
            });
          }
        },
      });










    }

  },



  onLoad(query) {
    var that = this;
    //获取省市区县数据
    area.getAreaInfo(function(arr) {
      areaInfo = arr;
      //获取省份数据
      getProvinceData(that);
    });

    my.getStorage({
      key: 'addressId', // 缓存数据的key
      success: (res) => {
        console.log(res.data)
        if (res.data == null) {
          that.setData({
            name: '',
            phone: '',
            address: '',
          })
          return;
        }
      },
    });
  },

  onShow() {
    var that = this;
    my.getNetworkType({
      success: (res) => {
        if (res.networkAvailable) {
          that.setData({
            outline: false,
          })

          //获取useid
          my.getStorage({
            key: 'userId',
            success: function(res) {
              console.log('1111', res)
              if (res.data == null) {
                that.setData({
                  userId: ''
                })
              } else {
                that.setData({
                  userId: res.data
                })
              }
            },
            fail: function(res) {
              my.alert({ content: res.errorMessage });
            }
          })
          //获取openid
          my.getStorage({
            key: 'openid',
            success: function(res) {
              that.setData({
                openId: res.data
              })
            },
            fail: function(res) {
              my.alert({ content: res.errorMessage });
            }
          })
          //获deviceid
          my.getStorage({
            key: 'deviceid',
            success: function(res) {
              that.setData({
                deviceid: res.data
              })
            },
            fail: function(res) {
              my.alert({ content: res.errorMessage });
            }
          })
          // 获取token
          my.getStorage({
            key: 'token',
            success: function(res) {
              that.setData({
                token: res.data
              })
            },
            fail: function(res) {
              my.alert({ content: res.errorMessage });
            }
          })

          that.mycoupon()
          that.myaddress()
        } else {
          that.setData({
            outline: true
          })
        }
      }
    })
  },

  onHide() {
    // 页面隐藏
  },
  onUnload() {
    // 页面被关闭
  },
  onTitleClick() {
    // 标题被点击
  },
  onPullDownRefresh() {
    // 页面被下拉
  },
  onReachBottom() {
    // 页面被拉到底部
  },
  bindKeyInput(e) {
    this.setData({
      code: e.detail.value
    });
  },
  onShareAppMessage() {
    // 返回自定义分享信息
    return {
      title: 'My App',
      desc: 'My App description',
      path: 'pages/index/index',
    };
  },
  onReady: function() {

  },

});
// ---------------- 分割线 ----------------
//动画事件
function animationEvents(that, moveY, show) {
  console.log("moveY:" + moveY + "\nshow:" + show);
  that.animation = my.createAnimation({
    transformOrigin: "50% 50%",
    duration: 400,
    timingFunction: "ease",
    delay: 0
  })
  that.animation.translateY(moveY + 'vh').step()

  that.setData({
    animation: that.animation.export(),
    show: show
  })
}

//获取省份数据
function getProvinceData(that) {
  var num = 0;
  for (var i = 0; i < areaInfo.length; i++) {
    provinces[num] = areaInfo[i];
    num++;
  }
  that.setData({
    provinces: provinces
  })
  //初始化调一次可更改
  getCityArr(0, that);
  getCountyInfo(0, 0, that);
  that.setData({
    province: "北京市",
    city: "北京市",
    region: "东城区",
  })

}
// 获取地级市数据
function getCityArr(count, that) {
  var num = 0;
  for (var i = 0; i < provinces[count].children.length; i++) {
    citys[num] = provinces[count].children[i]
    num++;
  }
  if (citys.length == 0) {
    citys[0] = {
      name: ''
    };
  }
  that.setData({
    city: "",
    citys: citys,
    value: [count, 0, 0]
  })
}
// 获取区县数据
function getCountyInfo(column0, column1, that) {
  var num = 0;
  for (var i = 0; i < citys[column1].children.length; i++) {
    countys[num] = citys[column1].children[i]
    num++;
  }
  if (countys.length == 0) {
    countys[0] = {
      name: ''
    };
  }
  that.setData({
    region: "",
    countys: countys,
    value: [column0, column1, 0]
  })
}